// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'package:hawk/hawk.dart';
import 'package:http/http.dart' as http;
import 'package:nim_core/nim_core.dart';
import 'package:path_provider/path_provider.dart';
import 'package:universal_io/io.dart';
import 'dart:io';

import '../main_test.dart';
import 'method_name_value.dart';

Future<String?> networkUrlToBase64(String? url) async {
  if (url == null) {
    return null;
  }
  http.Response response = await http.get(Uri.parse(url));
  final bytes = response.bodyBytes;
  final mimeType = response.headers['content-type']?.split(';')[0] ??
      'application/octet-stream';
  return Uri.dataFromBytes(bytes, mimeType: mimeType).toString();
}

// 为防止冲突，先单独建文件，最后再与handle_send_message_case合并
class HandleMessageCase extends HandleBaseCase {
  HandleMessageCase();

  @override
  Future<ResultBean?> handle(event) async {
    super.handle(event);

    var inputParams = Map<String, dynamic>();
    if (params != null && params!.length > 0) {
      inputParams = params![0] as Map<String, dynamic>;
    }
    if (className?.trim() != 'MessageService' &&
        className?.trim() != 'MessageBuilder') {
      return null;
    }
    switch (methodName) {
      case 'onMessage':
        subsriptions
            .add(NimCore.instance.messageService.onMessage.listen((event) {
          print('Test_Observer onMessage ${event.toString()}');
          //延时两秒上报，解决断言时序问题
          sleep(Duration(seconds: 2));
          IntegratedManager.instance.report('onMessage',
              ResultBean(code: 0, data: event.map((e) => e.toMap()).toList()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onMessageReceipt':
        subsriptions.add(
            NimCore.instance.messageService.onMessageReceipt.listen((event) {
          print('Test_Observer onMessageReceipt ${event.toString()}');
          IntegratedManager.instance.report('onMessageReceipt',
              ResultBean(code: 0, data: event.map((e) => e.toMap()).toList()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onMessageStatus':
        subsriptions.add(
            NimCore.instance.messageService.onMessageStatus.listen((event) {
          print('Test_Observer onMessageStatus ${event.toString()}');
          IntegratedManager.instance.report(
              'onMessageStatus', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onMessagePinNotify':
        NimCore.instance.messageService.onMessagePinNotify.listen((event) {
          print('Test_Observer onMessagePinNotify ${event.toString()}');
          IntegratedManager.instance.report('onMessagePinNotify',
              ResultBean(code: 0, data: event.pin.toMap()));
        });
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onTeamMessageReceipt':
        subsriptions.add(NimCore.instance.messageService.onTeamMessageReceipt
            .listen((event) {
          print('Test_Observer onTeamMessageReceipt ${event.toString()}');
          //延时两秒上报，解决断言时序问题
          sleep(Duration(seconds: 2));
          IntegratedManager.instance.report('onTeamMessageReceipt',
              ResultBean(code: 0, data: event.map((e) => e.toMap()).toList()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onAttachmentProgress':
        subsriptions.add(NimCore.instance.messageService.onAttachmentProgress
            .listen((event) {
          print('Test_Observer onAttachmentProgress ${event.toString()}');
          IntegratedManager.instance.report(
              'onAttachmentProgress', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onMessageRevoked':
        subsriptions.add(
            NimCore.instance.messageService.onMessageRevoked.listen((event) {
          print('Test_Observer onMessageRevoked ${event.toString()}');
          IntegratedManager.instance.report(
              'onMessageRevoked', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onBroadcastMessage':
        subsriptions.add(
            NimCore.instance.messageService.onBroadcastMessage.listen((event) {
          print('Test_Observer onBroadcastMessage ${event.toString()}');
          IntegratedManager.instance.report(
              'onBroadcastMessage', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onSessionUpdate':
        subsriptions.add(
            NimCore.instance.messageService.onSessionUpdate.listen((event) {
          print('Test_Observer onSessionUpdate ${event.toString()}');
          IntegratedManager.instance.report('onSessionUpdate',
              ResultBean(code: 0, data: event.map((e) => e.toMap()).toList()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onSessionDelete':
        subsriptions.add(
            NimCore.instance.messageService.onSessionDelete.listen((event) {
          print('Test_Observer onSessionDelete ${event.toString()}');
          IntegratedManager.instance.report(
              'onSessionDelete', ResultBean(code: 0, data: event?.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onMySessionUpdate':
        subsriptions.add(
            NimCore.instance.messageService.onMySessionUpdate.listen((event) {
          print('Test_Observer onMySessionUpdate ${event.toString()}');
          IntegratedManager.instance.report(
              'onMySessionUpdate', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onQuickCommentAdd':
        subsriptions.add(
            NimCore.instance.messageService.onQuickCommentAdd.listen((event) {
          print('Test_Observer onQuickCommentAdd ${event.toString()}');
          IntegratedManager.instance.report(
              'onQuickCommentAdd', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onQuickCommentRemove':
        subsriptions.add(NimCore.instance.messageService.onQuickCommentRemove
            .listen((event) {
          print('Test_Observer onQuickCommentRemove ${event.toString()}');
          IntegratedManager.instance.report(
              'onQuickCommentRemove', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onSyncStickTopSession':
        subsriptions.add(NimCore.instance.messageService.onSyncStickTopSession
            .listen((event) {
          print('Test_Observer onSyncStickTopSession ${event.toString()}');
          IntegratedManager.instance.report('onSyncStickTopSession',
              ResultBean(code: 0, data: event.map((e) => e.toMap()).toList()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onStickTopSessionAdd':
        subsriptions.add(NimCore.instance.messageService.onStickTopSessionAdd
            .listen((event) {
          print('Test_Observer onStickTopSessionAdd ${event.toString()}');
          IntegratedManager.instance.report(
              'onStickTopSessionAdd', ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onStickTopSessionRemove':
        subsriptions.add(NimCore.instance.messageService.onStickTopSessionRemove
            .listen((event) {
          print('Test_Observer onStickTopSessionRemove ${event.toString()}');
          IntegratedManager.instance.report('onStickTopSessionRemove',
              ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'onStickTopSessionUpdate':
        subsriptions.add(NimCore.instance.messageService.onStickTopSessionUpdate
            .listen((event) {
          print('Test_Observer onStickTopSessionUpdate ${event.toString()}');
          IntegratedManager.instance.report('onStickTopSessionUpdate',
              ResultBean(code: 0, data: event.toMap()));
        }));
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'replyMessage':
        if (inputParams['msg']['messageAttachment']['base64'] != null) {
          inputParams['msg']['messageAttachment']['base64'] =
              await networkUrlToBase64(
                  inputParams['msg']['messageAttachment']['base64']);
        }
        if (inputParams['replyMsg']['messageAttachment']['base64'] != null) {
          inputParams['replyMsg']['messageAttachment']['base64'] =
              await networkUrlToBase64(
                  inputParams['replyMsg']['messageAttachment']['base64']);
        }
        NIMResult<void> result = await NimCore.instance.messageService
            .replyMessage(
                msg: NIMMessage.fromMap(inputParams['msg']),
                replyMsg: NIMMessage.fromMap(inputParams['replyMsg']),
                resend: inputParams['resend'] as bool? ?? false);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendMessageReceipt':
        NIMResult<void> result = await NimCore.instance.messageService
            .sendMessageReceipt(
                sessionId: inputParams['sessionId'],
                message: NIMMessage.fromMap(inputParams['message']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createEmptyMessage':
        NIMResult<NIMMessage> result = await MessageBuilder.createEmptyMessage(
            sessionId: inputParams['sessionId'],
            sessionType:
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
            timestamp: inputParams['timestamp'] as int);
        handleCaseResult = ResultBean(
            code: result.code, data: result.data?.toMap(), message: methodName);
        break;

      case 'createTextMessage':
        NIMResult<NIMMessage> result = await MessageBuilder.createTextMessage(
            sessionId: inputParams['sessionId'] as String,
            sessionType: NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            text: inputParams['text'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createImageMessage':
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await MessageBuilder.createImageMessage(
            sessionId: inputParams['sessionId'] as String,
            sessionType: NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            filePath: filePath,
            fileSize: inputParams['fileSize'] as int,
            base64: inputParams['base64'] as String?,
            displayName: inputParams['displayName'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createAudioMessage':
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await MessageBuilder.createAudioMessage(
          sessionId: inputParams['sessionId'] as String,
          sessionType: NIMSessionTypeConverter()
              .fromValue(inputParams['sessionType'] as String),
          filePath: filePath,
          fileSize: inputParams['fileSize'] as int,
          base64: inputParams['base64'] as String?,
          duration: inputParams['duration'] as int,
          displayName: inputParams['displayName'] as String?,
        );
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createLocationMessage':
        NIMResult<NIMMessage> result =
            await MessageBuilder.createLocationMessage(
                sessionId: inputParams['sessionId'] as String,
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType'] as String),
                latitude: inputParams['latitude'],
                longitude: inputParams['longitude'],
                address: inputParams['address']);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createVideoMessage':
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await MessageBuilder.createVideoMessage(
            sessionId: inputParams['sessionId'] as String,
            sessionType: NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            filePath: filePath,
            fileSize: inputParams['fileSize'] as int,
            duration: inputParams['duration'] as int,
            base64: inputParams['base64'] as String?,
            displayName: inputParams['displayName'] as String,
            width: inputParams['width'] as int,
            height: inputParams['height'] as int);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'createFileMessage':
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await MessageBuilder.createFileMessage(
          sessionId: inputParams['sessionId'] as String,
          sessionType: NIMSessionTypeConverter()
              .fromValue(inputParams['sessionType'] as String),
          filePath: filePath,
          fileSize: inputParams['fileSize'] as int,
          base64: inputParams['base64'] as String?,
          displayName: inputParams['displayName'] as String,
        );
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createTipMessage':
        NIMResult<NIMMessage> result = await MessageBuilder.createTipMessage(
            sessionId: inputParams['sessionId'] as String,
            sessionType: NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            content: inputParams['content'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'createCustomMessage':
        NIMResult<NIMMessage> result = await MessageBuilder.createCustomMessage(
            sessionId: inputParams['sessionId'] as String,
            sessionType: NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            content: inputParams['content'] as String?,
            attachment: inputParams['attachment'] == null
                ? null
                : NIMCustomMessageAttachment.fromMap(inputParams['attachment']),
            config: inputParams['config'] == null
                ? null
                : NIMCustomMessageConfig.fromMap(inputParams['config']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;

      case 'sendMessage':
        if (inputParams['message']['messageAttachment']['base64'] != null) {
          inputParams['message']['messageAttachment']['base64'] =
              await networkUrlToBase64(
                  inputParams['message']['messageAttachment']['base64']);
        }
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendMessage(
                message: NIMMessage.fromMap(inputParams['message']),
                resend: inputParams['resend'] as bool? ?? false);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: 'sendMessage');
        break;
      case 'sendMessageNeedAck':
        var message = NIMMessage.fromMap(inputParams['message']);
        message.messageAck = true;
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendMessage(
                message: message,
                resend: inputParams['resend'] as bool? ?? false);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case saveMessage:
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .saveMessage(
                message: NIMMessage.fromMap(inputParams['message']),
                fromAccount: inputParams['fromAccount'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'saveMessageToLocalEx':
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .saveMessageToLocalEx(
                message: NIMMessage.fromMap(inputParams['message']),
                time: inputParams['time'] as int);
        handleCaseResult = ResultBean(
            code: result.code, data: result.data?.toMap(), message: methodName);
        break;
      case updateMessage:
        NIMResult<void> result = await NimCore.instance.messageService
            .updateMessage(NIMMessage.fromMap(inputParams['message']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'deleteChattingHistoryList':
        var paramList = inputParams['msgList'] as List<dynamic>;
        List<NIMMessage> msgList =
            paramList.map((e) => NIMMessage.fromMap(e)).toList();
        await NimCore.instance.messageService
            .deleteChattingHistoryList(msgList, inputParams['ignore']);
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case cancelUploadAttachment:
        NIMResult<void> result = await NimCore.instance.messageService
            .cancelUploadAttachment(NIMMessage.fromMap(inputParams['message']));
        handleCaseResult = ResultBean(
            code: result.code,
            data: result.toMapD(),
            message: 'cancelUploadAttachment');
        break;
      case forwardMessage:
        NIMResult<void> result = await NimCore.instance.messageService
            .forwardMessage(
                NIMMessage.fromMap(inputParams['message']),
                inputParams['sessionId'],
                NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType'] as String));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case revokeMessage:
        NIMResult<void> result = await NimCore.instance.messageService
            .revokeMessage(
                message: NIMMessage.fromMap(inputParams['message']),
                customApnsText: inputParams['customApnsText'] as String?,
                shouldNotifyBeCount:
                    inputParams['shouldNotifyBeCount'] as bool?,
                postscript: inputParams['postscript'] as String?,
                attach: inputParams['attach'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'voiceToText':
        NIMResult<void> result = await NimCore.instance.messageService
            .voiceToText(
                message: NIMMessage.fromMap(inputParams['message']),
                scene: inputParams['scene'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryThreadTalkHistory':
        NIMResult<NIMThreadTalkHistory> result =
            await NimCore.instance.messageService.queryThreadTalkHistory(
                anchor: NIMMessage.fromMap(inputParams['anchor']),
                fromTime: inputParams['fromTime'] as int,
                toTime: inputParams['toTime'] as int,
                limit: inputParams['limit'] as int,
                direction:
                    convertStringToQueryDirection(inputParams['direction']),
                persist: inputParams['persist'] as bool? ?? false);
        handleCaseResult = ResultBean(
            code: result.code, data: result.data?.toMap(), message: methodName);
        break;
      case 'setChattingAccount':
        NIMResult<void> result = await NimCore.instance.messageService
            .setChattingAccount(
                sessionId: inputParams['sessionId'] as String,
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType'] as String));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'clearSessionUnreadCount':
        var sessionInfoList = inputParams['sessionInfoList'] as List<dynamic>;
        List<NIMSessionInfo> infoList =
            sessionInfoList.map((e) => NIMSessionInfo.fromMap(e)).toList();
        NIMResult<List<NIMSessionInfo>> result = await NimCore
            .instance.messageService
            .clearSessionUnreadCount(infoList);
        handleCaseResult = ResultBean(
            code: result.code,
            data: result.data?.map((e) => e.toMap()).toList(),
            message: methodName);
        break;
      case 'clearAllSessionUnreadCount':
        NIMResult<void> result =
            await NimCore.instance.messageService.clearAllSessionUnreadCount();
        handleCaseResult =
            ResultBean(code: result.code, data: null, message: methodName);
        break;
      case "queryLastMessage":
        var account = inputParams['account'] as String;
        var sessionType = NIMSessionTypeConverter()
            .fromValue(inputParams['sessionType'] as String);
        final result = await NimCore.instance.messageService
            .queryLastMessage(account, sessionType);
        handleCaseResult =
            ResultBean(code: result.code, data: result.toMapD(), message: '');
        break;
      case 'queryMessageListEx':
        var message = NIMMessage.fromMap(inputParams['anchor']);
        var direction =
            convertStringToQueryDirection(inputParams['queryDirection']);
        var limit = inputParams['limit'] as int;
        final result = await NimCore.instance.messageService
            .queryMessageListEx(message, direction, limit);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'getMessagesDynamically':
        final result = await NimCore.instance.messageService
            .getMessagesDynamically(
                GetMessagesDynamicallyParam.fromMap(inputParams));
        handleCaseResult = ResultBean(
            code: result.code, data: result.data?.toMap(), message: methodName);
        break;
      case 'clearServerHistory':
        await NimCore.instance.messageService.clearServerHistory(
            inputParams['sessionId'] as String,
            NIMSessionTypeConverter()
                .fromValue(inputParams['sessionType'] as String),
            inputParams['sync'] as bool);
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'addQuickComment':
        var pushPayload = (inputParams['pushPayload'] as Map).map(
            (key, value) => MapEntry<String, Object>(key.toString(), value));
        print('================addQuickComment$pushPayload');
        NIMResult<int> result = await NimCore.instance.messageService
            .addQuickComment(
                NIMMessage.fromMap(inputParams['msg']),
                inputParams['replyType'] as int,
                inputParams['ext'] as String,
                inputParams['needPush'] as bool,
                inputParams['needBadge'] as bool,
                inputParams['pushTitle'] as String,
                inputParams['pushContent'] as String,
                pushPayload);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'removeQuickComment':
        var pushPayload = (inputParams['pushPayload'] as Map).map(
            (key, value) => MapEntry<String, Object>(key.toString(), value));
        NIMResult<void> result = await NimCore.instance.messageService
            .removeQuickComment(
                NIMMessage.fromMap(inputParams['msg']),
                inputParams['replyType'] as int,
                inputParams['ext'] as String,
                inputParams['needPush'] as bool,
                inputParams['needBadge'] as bool,
                inputParams['pushTitle'] as String,
                inputParams['pushContent'] as String,
                pushPayload);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryQuickComment':
        var paramList = inputParams['msgList'] as List<dynamic>;
        List<NIMMessage> msgList =
            paramList.map((e) => NIMMessage.fromMap(e)).toList();
        NIMResult<List<NIMQuickCommentOptionWrapper>> result =
            await NimCore.instance.messageService.queryQuickComment(msgList);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'addStickTopSession':
        NIMResult<NIMStickTopSessionInfo> result =
            await NimCore.instance.messageService.addStickTopSession(
                inputParams['sessionId'],
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
                inputParams['ext']);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendTextMessage':
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendTextMessage(
                sessionId: inputParams['sessionId'],
                text: inputParams['text'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendImageMessage':
        String? base64;
        if (kIsWeb) {
          base64 = await networkUrlToBase64(inputParams['base64'] as String?);
        }
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendImageMessage(
                sessionId: inputParams['sessionId'],
                filePath: filePath,
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                fileSize: inputParams['fileSize'] as int,
                displayName: inputParams['displayName'] as String,
                nosScene: inputParams['nosScene'],
                base64: base64,
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendAudioMessage':
        String? base64;
        if (kIsWeb) {
          base64 = await networkUrlToBase64(inputParams['base64'] as String?);
        }
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendAudioMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                filePath: filePath,
                fileSize: inputParams['fileSize'] as int,
                duration: inputParams['duration'] as int,
                base64: base64,
                displayName: inputParams['displayName'] as String,
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendLocationMessage':
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendLocationMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                latitude: inputParams['latitude'],
                longitude: inputParams['longitude'],
                address: inputParams['address'],
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendVideoMessage':
        String? base64;
        if (kIsWeb) {
          base64 = await networkUrlToBase64(inputParams['base64'] as String?);
        }
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendVideoMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                filePath: filePath,
                fileSize: inputParams['fileSize'] as int,
                duration: inputParams['duration'] as int,
                width: inputParams['width'] as int,
                height: inputParams['height'] as int,
                displayName: inputParams['displayName'] as String,
                base64: base64,
                nosScene: inputParams['nosScene'],
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendFileMessage':
        String? base64;
        if (kIsWeb) {
          base64 = await networkUrlToBase64(inputParams['base64'] as String?);
        }
        var filePath = inputParams['filePath'] as String;
        if (!kIsWeb &&
            (Platform.isIOS || Platform.isMacOS) &&
            filePath.isNotEmpty) {
          var rootPath = await getApplicationDocumentsDirectory();
          filePath = '${rootPath.path}/$filePath';
        }
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendFileMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                filePath: filePath,
                fileSize: inputParams['fileSize'] as int,
                displayName: inputParams['displayName'] as String,
                base64: base64,
                nosScene: inputParams['nosScene'],
                action: inputParams['action'] as MessageAction?);
        print('===================>sendFileMessage$result');
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendTipMessage':
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendTipMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                content: inputParams['content'] as String?,
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendCustomMessage':
        NIMResult<NIMMessage> result = await NimCore.instance.messageService
            .sendCustomMessage(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                content: inputParams['content'] as String?,
                attachment: inputParams['attachment'] == null
                    ? null
                    : NIMCustomMessageAttachment.fromMap(
                        inputParams['attachment']),
                config: inputParams['config'] == null
                    ? null
                    : NIMCustomMessageConfig.fromMap(inputParams['config']),
                action: inputParams['action'] as MessageAction?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendMessageReceipt':
        NIMResult<void> result = await NimCore.instance.messageService
            .sendMessageReceipt(
                sessionId: inputParams['sessionId'],
                message: NIMMessage.fromMap(inputParams['message']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'sendTeamMessageReceipt':
        NIMResult<void> result = await NimCore.instance.messageService
            .sendTeamMessageReceipt(NIMMessage.fromMap(inputParams['message']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryMessageListByUuid':
        var paramList = inputParams['uuids'] as List<dynamic>;
        List<String> uuids = paramList.map((e) => e.toString()).toList();
        NIMResult<void> result = await NimCore.instance.messageService
            .queryMessageListByUuid(
                uuids,
                inputParams['sessionId'],
                NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'deleteChattingHistory':
        await NimCore.instance.messageService.deleteChattingHistory(
            NIMMessage.fromMap(inputParams['anchor']), inputParams['ignore']);
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'clearChattingHistory':
        var account = inputParams['account'] as String;
        var sessionType = NIMSessionTypeConverter()
            .fromValue(inputParams['sessionType'] as String);
        var ignore = inputParams['ignore'] as bool?;
        await NimCore.instance.messageService
            .clearChattingHistory(account, sessionType, ignore);
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'clearMsgDatabase':
        await NimCore.instance.messageService
            .clearMsgDatabase(inputParams['clearRecent']);
        handleCaseResult = ResultBean(code: 0, data: null, message: methodName);
        break;
      case 'pullMessageHistory':
        NIMResult<List<NIMMessage>> result =
            await NimCore.instance.messageService.pullMessageHistory(
                NIMMessage.fromMap(inputParams['anchor']),
                inputParams['limit'] as int,
                inputParams['persist'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'pullMessageHistoryExType':
        var paramsList = inputParams['messageTypeList'] as List<dynamic>;
        List<NIMMessageType> messageTypeList = paramsList
            .map((e) => NIMMessageTypeConverter().fromValue(e))
            .toList();
        NIMResult<List<NIMMessage>> result =
            await NimCore.instance.messageService.pullMessageHistoryExType(
                NIMMessage.fromMap(inputParams['anchor']),
                inputParams['toTime'] as int,
                inputParams['limit'],
                convertStringToQueryDirection(inputParams['direction']),
                messageTypeList,
                inputParams['persist']);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case "deleteMsgSelf":
        var message = NIMMessage.fromMap(inputParams["message"]);
        var result = await NimCore.instance.messageService
            .deleteMsgSelf(message, inputParams['ext']);
        print(
            '=========>>MessageService:deleteMsgSelf=${result.code}：${result.errorDetails}');
        handleCaseResult =
            ResultBean(code: result.code, data: result.toMapD(), message: '');
        break;
      case "deleteMsgListSelf":
        var messageList = inputParams['msgList'] as List<dynamic>;
        List<NIMMessage> mList =
            messageList.map((e) => NIMMessage.fromMap(e)).toList();
        var ext = inputParams['ext'] as String;
        var result =
            await NimCore.instance.messageService.deleteMsgListSelf(mList, ext);
        handleCaseResult =
            ResultBean(code: result.code, data: result.toMapD(), message: '');
        break;
      case 'searchMessage':
        NIMResult<List<NIMMessage>> result =
            await NimCore.instance.messageService.searchMessage(
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
                inputParams['sessionId'] as String,
                MessageSearchOption.fromMap(
                    inputParams['searchOption'] as Map<String, dynamic>));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'searchAllMessage':
        NIMResult<List<NIMMessage>> result = await NimCore
            .instance.messageService
            .searchAllMessage(MessageSearchOption.fromMap(
                inputParams['searchOption'] as Map<String, dynamic>));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'searchRoamingMsg':
        NIMResult<List<NIMMessage>> result =
            await NimCore.instance.messageService.searchRoamingMsg(
                inputParams['otherAccid'] as String,
                inputParams['fromTime'] as int,
                inputParams['endTime'] as int,
                inputParams['keyword'] as String,
                inputParams['limit'] as int,
                inputParams['reverse'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'searchCloudMessageHistory':
        var config = MessageKeywordSearchConfig.fromMap(
            inputParams['config'] as Map<String, dynamic>);
        print('===========>searchCloudMessageHistory-config$config');
        NIMResult<List<NIMMessage>> result = await NimCore
            .instance.messageService
            .searchCloudMessageHistory(config);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'downloadAttachment':
        NIMResult<void> result = await NimCore.instance.messageService
            .downloadAttachment(
                message: NIMMessage.fromMap(inputParams['message']),
                thumb: inputParams['thumb'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'refreshTeamMessageReceipt':
        var paramList = inputParams['messageList'] as List<dynamic>;
        List<NIMMessage> msgList =
            paramList.map((e) => NIMMessage.fromMap(e)).toList();
        NIMResult<void> result = await NimCore.instance.messageService
            .refreshTeamMessageReceipt(msgList);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'fetchTeamMessageReceiptDetail':
        var paramList = inputParams['accountList'] as List<dynamic>;
        List<String> accountList = paramList.map((e) => e.toString()).toList();
        NIMResult<NIMTeamMessageAckInfo> result =
            await NimCore.instance.messageService.fetchTeamMessageReceiptDetail(
                message: NIMMessage.fromMap(inputParams['message']),
                accountList: accountList);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryTeamMessageReceiptDetail':
        var paramList = inputParams['accountList'] as List<dynamic>;
        List<String> accountList = paramList.map((e) => e.toString()).toList();
        NIMResult<NIMTeamMessageAckInfo> result =
            await NimCore.instance.messageService.queryTeamMessageReceiptDetail(
                message: NIMMessage.fromMap(inputParams['message']),
                accountList: accountList);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'addCollect':
        NIMResult<NIMCollectInfo> result = await NimCore.instance.messageService
            .addCollect(
                type: inputParams['type'] as int,
                data: inputParams['data'] as String,
                ext: inputParams['ext'] as String?,
                uniqueId: inputParams['uniqueId'] as String?);
        print('=============>addCollect-result$result');
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'removeCollect':
        var paramList = inputParams['collects'] as List<dynamic>;
        List<NIMCollectInfo> collects = paramList
            .map((e) => NIMCollectInfo.fromMap(e as Map<String, dynamic>))
            .toList();
        NIMResult<int> result =
            await NimCore.instance.messageService.removeCollect(collects);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateCollect':
        NIMResult<NIMCollectInfo> result = await NimCore.instance.messageService
            .updateCollect(NIMCollectInfo.fromMap(inputParams['info']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryCollect':
        NIMResult<NIMCollectInfoQueryResult> result =
            await NimCore.instance.messageService.queryCollect(
                anchor: inputParams['anchor'] == null
                    ? null
                    : NIMCollectInfo.fromMap(inputParams['anchor']),
                toTime: (inputParams['toTime'] as num).toInt(),
                type: inputParams['type'] as int?,
                limit: inputParams['limit'] as int,
                direction:
                    convertStringToQueryDirection(inputParams['direction']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'addMessagePin':
        NIMResult<void> result = await NimCore.instance.messageService
            .addMessagePin(NIMMessage.fromMap(inputParams['message']),
                inputParams['ext'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateMessagePin':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateMessagePin(NIMMessage.fromMap(inputParams['message']),
                inputParams['ext'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'removeMessagePin':
        NIMResult<void> result = await NimCore.instance.messageService
            .removeMessagePin(NIMMessage.fromMap(inputParams['message']),
                inputParams['ext'] as String?);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryMessagePinForSession':
        NIMResult<List<NIMMessagePin>> result =
            await NimCore.instance.messageService.queryMessagePinForSession(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryReplyCountInThreadTalkBlock':
        NIMResult<int> result = await NimCore.instance.messageService
            .queryReplyCountInThreadTalkBlock(
                NIMMessage.fromMap(inputParams['msg']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'querySessionList':
        NIMResult<List<NIMSession>> result = await NimCore
            .instance.messageService
            .querySessionList(inputParams['limit'] as int?);
        handleCaseResult = ResultBean(
            code: result.code,
            data: result.toMapD(listKey: 'resultList'),
            message: methodName);
        break;
      case 'querySessionListFiltered':
        var messageTypeList =
            inputParams['filterMessageTypeList'] as List<dynamic>;
        List<NIMMessageType> filterMessageTypeList = messageTypeList
            .map((e) => NIMMessageTypeConverter().fromValue(e))
            .toList();
        NIMResult<List<NIMSession>> result = await NimCore
            .instance.messageService
            .querySessionListFiltered(filterMessageTypeList);
        handleCaseResult = ResultBean(
            code: result.code,
            data: result.toMapD(listKey: 'resultList'),
            message: methodName);
        break;
      case 'querySession':
        NIMResult<NIMSession> result = await NimCore.instance.messageService
            .querySession(NIMSessionInfo.fromMap(inputParams['sessionInfo']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'createSession':
        NIMResult<NIMSession> result = await NimCore.instance.messageService
            .createSession(
                sessionId: inputParams['sessionId'],
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']),
                tag: inputParams['tag'] as int,
                time: inputParams['time'] as int,
                linkToLastMessage: inputParams['linkToLastMessage'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateSession':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateSession(
                session: NIMSession.fromMap(inputParams['session']),
                needNotify: inputParams['needNotify'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateSessionWithMessage':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateSessionWithMessage(
                message: NIMMessage.fromMap(inputParams['message']),
                needNotify: inputParams['needNotify'] as bool);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryTotalUnreadCount':
        var type;
        switch (inputParams['queryType']) {
          case 'notifyOnly':
            type = NIMUnreadCountQueryType.notifyOnly;
            break;
          case 'noDisturbOnly':
            type = NIMUnreadCountQueryType.noDisturbOnly;
            break;
          default:
            type = NIMUnreadCountQueryType.all;
        }
        NIMResult<int> result = await NimCore.instance.messageService
            .queryTotalUnreadCount(queryType: type);
        handleCaseResult = ResultBean(
            code: result.code, data: result.data, message: methodName);
        break;
      case 'setChattingAccount':
        NIMResult<void> result = await NimCore.instance.messageService
            .setChattingAccount(
                sessionId: inputParams['sessionId'] as String,
                sessionType: NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'deleteSession':
        NIMResult<void> result = await NimCore.instance.messageService
            .deleteSession(
                sessionInfo: NIMSessionInfo.fromMap(inputParams['sessionInfo']),
                deleteType:
                    convertStringToSessionDeleteType(inputParams['deleteType']),
                sendAck: inputParams['sendAck']);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'checkLocalAntiSpam':
        NIMResult<NIMLocalAntiSpamResult> result =
            await NimCore.instance.messageService.checkLocalAntiSpam(
                inputParams['content'] as String,
                inputParams['replacement'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryMySessionList':
        NIMResult<RecentSessionList> result =
            await NimCore.instance.messageService.queryMySessionList(
                inputParams['minTimestamp'] as int,
                inputParams['maxTimestamp'] as int,
                inputParams['needLastMsg'] as int,
                inputParams['limit'] as int,
                inputParams['hasMore'] as int);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryMySession':
        NIMResult<RecentSession> result = await NimCore.instance.messageService
            .queryMySession(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateMySession':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateMySession(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
                inputParams['ext'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'deleteMySession':
        var sessionInfoList = (inputParams['sessionList'] as List)
            .map((e) => NIMMySessionKey(
                sessionType:
                    NIMSessionTypeConverter().fromValue(e['sessionType']),
                sessionId: e['sessionId']))
            .toList();
        NIMResult<void> result = await NimCore.instance.messageService
            .deleteMySession(sessionInfoList);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'removeStickTopSession':
        NIMResult<void> result = await NimCore.instance.messageService
            .removeStickTopSession(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
                inputParams['ext'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateStickTopSession':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateStickTopSession(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter().fromValue(inputParams['sessionType']),
                inputParams['ext'] as String);
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryStickTopSession':
        NIMResult<List<NIMStickTopSessionInfo>> result =
            await NimCore.instance.messageService.queryStickTopSession();
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'queryRoamMsgHasMoreTime':
        NIMResult<int> result = await NimCore.instance.messageService
            .queryRoamMsgHasMoreTime(
                inputParams['sessionId'] as String,
                NIMSessionTypeConverter()
                    .fromValue(inputParams['sessionType']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      case 'updateRoamMsgHasMoreTag':
        NIMResult<void> result = await NimCore.instance.messageService
            .updateRoamMsgHasMoreTag(NIMMessage.fromMap(inputParams['newTag']));
        handleCaseResult = ResultBean(
            code: result.code, data: result.toMapD(), message: methodName);
        break;
      default:
        break;
    }
    return handleCaseResult;
  }

  QueryDirection convertStringToQueryDirection(String param) {
    return param == 'QUERY_NEW'
        ? QueryDirection.QUERY_NEW
        : QueryDirection.QUERY_OLD;
  }

  NIMSessionDeleteType convertStringToSessionDeleteType(String param) {
    if (param == 'local') return NIMSessionDeleteType.local;
    if (param == 'remote') return NIMSessionDeleteType.remote;
    return NIMSessionDeleteType.localAndRemote;
  }
}

extension NIMResultToMap on NIMResult {
  nimMessageKeyToMap(NIMMessageKey key) => <String, dynamic>{
        'sessionType': NIMSessionTypeEnumMap[key.sessionType],
        'fromAccount': key.fromAccount,
        'toAccount': key.toAccount,
        'time': key.time,
        'serverId': key.serverId,
        'uuid': key.uuid
      };

  recentSessionToMap(RecentSession session) => <String, dynamic>{
        'sessionId': session.sessionId,
        'updateTime': session.updateTime,
        'ext': session.ext,
        'lastMsg': session.lastMsg,
        'lastMsgType': session.lastMsgType,
        'recentSession': session.recentSession?.toMap(),
        'sessionType': NIMSessionTypeEnumMap[session.sessionType],
        'sessionTypePair': session.sessionTypePair,
        'revokeNotification': session.revokeNotification?.toMap(),
      };

  nIMStickTopSessionInfoToMap(NIMStickTopSessionInfo info) => <String, dynamic>{
        'sessionId': info.sessionId,
        'sessionType': NIMSessionTypeEnumMap[info.sessionType],
        'ext': info.ext,
        'createTime': info.createTime,
        'updateTime': info.updateTime
      };

  toMapD({String? listKey}) {
    var dataMap = null;
    if (data is NIMMessage) {
      dataMap = data.toMap();
    } else if (data is NIMThreadTalkHistory) {
      dataMap = data.toMap();
    } else if (data is List<NIMStickTopSessionInfo>) {
      dataMap = <String, dynamic>{
        'stickTopSessionInfoList':
            data.map((e) => nIMStickTopSessionInfoToMap(e)).toList()
      };
    } else if (data is RecentSession) {
      dataMap = <String, dynamic>{
        'recentSession': recentSessionToMap(data),
      };
    } else if (data is RecentSessionList) {
      dataMap = <String, dynamic>{
        'mySessionList': <String, dynamic>{
          'hasMore': data.hasMore,
          'sessionList':
              data.sessionList?.map((e) => recentSessionToMap(e))?.toList(),
        },
      };
    } else if (data is NIMLocalAntiSpamResult) {
      dataMap = <String, dynamic>{
        'operator': data.operator,
        'content': data.content,
      };
    } else if (data is NIMSession) {
      dataMap = data.toMap();
    } else if (data is List<NIMSession>) {
      dataMap = <String, dynamic>{
        listKey ?? '': data.map((e) => e.toMap()).toList()
      };
    } else if (data is List<NIMMessagePin>) {
      dataMap = <String, dynamic>{
        'pinList': data.map((e) => e.toMap()).toList()
      };
    } else if (data is NIMCollectInfoQueryResult) {
      dataMap = <String, dynamic>{
        'totalCount': data.totalCount,
        'collects': data.collectList?.map((e) => e.toMap()).toList(),
      };
    } else if (data is NIMCollectInfo) {
      dataMap = data.toMap();
    } else if (data is NIMTeamMessageAckInfo) {
      dataMap = data.toMap();
    } else if (data is NIMStickTopSessionInfo) {
      dataMap = <String, dynamic>{
        'stickTopSessionInfo': nIMStickTopSessionInfoToMap(data),
      };
    } else if (data is List<NIMQuickCommentOptionWrapper>) {
      dataMap = <String, dynamic>{
        'quickCommentOptionWrapperList': data
            .map((e) => <String, dynamic>{
                  'quickCommentList': e.quickCommentList
                      ?.map((item) => <String, dynamic>{
                            'fromAccount': item.fromAccount,
                            'replyType': item.replyType,
                            'time': item.time,
                            'ext': item.ext,
                            'needPush': item.needPush,
                            'needBadge': item.needBadge,
                            'pushTitle': item.pushTitle,
                            'pushContent': item.pushContent,
                            'pushPayload': item.pushPayload
                          })
                      ?.toList(),
                  'key': e.key == null ? null : nimMessageKeyToMap(e.key!),
                  'modify': e.modify,
                  'time': e.time,
                })
            .toList()
      };
    } else if (data is List<NIMMessage>) {
      dataMap = <String, dynamic>{
        'messageList': data.map((e) => e.toMap()).toList()
      };
    }
    return {
      'code': code,
      'data': dataMap ?? data,
      'msg': errorDetails,
    };
  }
}

extension RecentSessionToMap on RecentSession {
  toMap() => <String, dynamic>{
        'sessionId': sessionId,
        'updateTime': updateTime,
        'ext': ext,
        'lastMsg': lastMsg,
        'lastMsgType': lastMsgType,
        'recentSession': recentSession?.toMap(),
        'sessionType': NIMSessionTypeEnumMap[sessionType],
        'sessionTypePair': sessionTypePair,
        'revokeNotification': revokeNotification?.toMap(),
      };
}

const NIMSessionTypeEnumMap = {
  NIMSessionType.none: 'none',
  NIMSessionType.p2p: 'p2p',
  NIMSessionType.team: 'team',
  NIMSessionType.superTeam: 'superTeam',
  NIMSessionType.system: 'system',
  NIMSessionType.ysf: 'ysf',
  NIMSessionType.chatRoom: 'chatRoom',
};

extension NIMHandleQuickCommentOptionToMap on NIMHandleQuickCommentOption {
  toMap() => <String, dynamic>{
        'key': key?.toMap(),
        'commentOption': commentOption?.toMap()
      };
}

extension NIMMessageKeyToMap on NIMMessageKey {
  toMap() => <String, dynamic>{
        'sessionType': NIMSessionTypeEnumMap[sessionType],
        'fromAccount': fromAccount,
        'toAccount': toAccount,
        'time': time,
        'serverId': serverId,
        'uuid': uuid
      };
}

extension NIMQuickCommentOptionToMap on NIMQuickCommentOption {
  toMap() => <String, dynamic>{
        'fromAccount': fromAccount,
        'replyType': replyType,
        'time': time,
        'ext': ext,
        'needPush': needPush,
        'needBadge': needBadge,
        'pushTitle': pushTitle,
        'pushContent': pushContent,
        'pushPayload': pushPayload
      };
}

extension NIMStickTopSessionInfoToMap on NIMStickTopSessionInfo {
  toMap() => <String, dynamic>{
        'sessionId': sessionId,
        'sessionType': NIMSessionTypeEnumMap[sessionType],
        'ext': ext,
        'createTime': createTime,
        'updateTime': updateTime
      };
}
